package com.pfsbuilder;

import java.io.File;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 * <p>
 * Title: PFS
 * </p>
 * 
 * <p>
 * Description:
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2005
 * </p>
 * 
 * <p>
 * Company: Petersoft
 * </p>
 * 
 * @author Peter
 * @version 2005
 */
public class FileSystemModel implements TreeModel {
	private Vector vector = new Vector();
	String root;

	public FileSystemModel() {
		this(System.getProperty("user.home"));
	}

	public FileSystemModel(String startPath) {
		root = startPath;
	}

	public Object getRoot() {
		return new File(root);
	}

	public Object getChild(Object parent, int index) {
		File directory = (File) parent;
		String[] children = directory.list();
		return new File(directory, children[index]);
	}

	public int getChildCount(Object parent) {
		File fileSysEntity = (File) parent;
		if (fileSysEntity.isDirectory()) {
			String[] children = fileSysEntity.list();
			return children.length;
		} else {
			return 0;
		}
	}

	public boolean isLeaf(Object node) {
		return ((File) node).isFile();
	}

	public void valueForPathChanged(TreePath path, Object newValue) {
	}

	public int getIndexOfChild(Object parent, Object child) {
		File directory = (File) parent;
		File fileSysEntity = (File) child;
		String[] children = directory.list();
		int result = -1;

		for (int i = 0; i < children.length; ++i) {
			if (fileSysEntity.getName().equals(children[i])) {
				result = i;
				break;
			}
		}

		return result;
	}

	public void addTreeModelListener(TreeModelListener listener) {
		if (listener != null && !vector.contains(listener)) {
			vector.addElement(listener);
		}
	}

	public void removeTreeModelListener(TreeModelListener listener) {
		if (listener != null) {
			vector.removeElement(listener);
		}
	}

	public void fireTreeNodesChanged(TreeModelEvent e) {
		Enumeration listeners = vector.elements();
		while (listeners.hasMoreElements()) {
			TreeModelListener listener = (TreeModelListener) listeners.nextElement();
			listener.treeNodesChanged(e);
		}
	}

	public void fireTreeNodesInserted(TreeModelEvent e) {
		Enumeration listeners = vector.elements();
		while (listeners.hasMoreElements()) {
			TreeModelListener listener = (TreeModelListener) listeners.nextElement();
			listener.treeNodesInserted(e);
		}

	}
}
